import axios from 'axios'
import { BASE_URL, TIME_OUT } from './config'
import { CustomRequestConfig, CustomInterceptors } from './type'
import LocalCache from '@/utils/LocalCache'

class Request {
  public instance
  public interceptors?: CustomInterceptors

  constructor(config: CustomRequestConfig) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors

    // 添加请求拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )

    // 添加响应拦截器
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )

    // 添加全局拦截器
    this.instance.interceptors.request.use((config) => {
      return config
    })

    this.instance.interceptors.response.use((config) => {
      return config.data
    })
  }
  request<T>(config: CustomRequestConfig<any>): Promise<T> {
    return new Promise((resolve) => {
      // 对每个请求进行拦截
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }
      this.instance.request<any, T>(config).then((res) => {
        if (config.interceptors?.responseInterceptor) {
          res = config.interceptors.responseInterceptor(res)
        }
        resolve(res)
      })
    })
  }

  get<T>(config: CustomRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'GET' })
  }

  post<T>(config: CustomRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'POST' })
  }

  delete<T>(config: CustomRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'DELETE' })
  }

  patch<T>(config: CustomRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'PATCH' })
  }
}

console.log(BASE_URL)
export default new Request({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  showLoading: true,
  interceptors: {
    requestInterceptor(config) {
      const token = LocalCache.getCache('token')
      config.headers!.authorization = `Bearer ${token}`
      return config
    }
  }
})
